﻿/*
 * 登录解析
 * 处理登录逻辑，验证客户段提交的账号密码，保存登录信息
 */
using OpenMms.Common.Auth;
using OpenMms.Common.Cathe;
using OpenMms.Common.Log;
using OpenMms.Common.Session;
using OpenMms.Domain.Enums;
using OpenMms.Domain.Interface;
using OpenMms.Domain.Models;
using OpenMms.Domain.ReponseModels;
using OpenMms.Domain.RequestModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenMms.Domain.BLL.User.Login
{
    /// <summary>
    /// 会员登录
    /// </summary>
    public  class LoginService: ILoginService
    {
        #region 获取实例
        //数据访问
        protected IBLLConstruct<UserInforMations> _repository { get; set; }
        //缓存
        protected ICacheContext _cache { get; set; }

        protected IAuth _auth { get; set; }

        public LoginService(IBLLConstruct<UserInforMations> repository, ICacheContext cache, IAuth auth)
        {
            this._cache = cache;
            this._repository = repository;
            this._auth = auth;
        }
        #endregion

        #region 验证信息 写入Cache
        /// <summary>
        /// 验证信息 写入Cache
        /// </summary>
        /// <param name="code"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public LoginResult Do(PassportLoginRequest request)
        {
            var result = new LoginResult();

            var userinfo = _repository.Find(u => u.UserCode == request.Account && u.UserPassWord == request.Password);

            if (userinfo == null)
            {
                result.Code = 500;
                result.Message = "用户名或密码不存在";
                return result;
            }

            MyLog.Log(userinfo, "User", "会员登录");

            UserAuthSession currentSession = SetCache(request, userinfo);
            result.Code = 200;
            result.Token = currentSession.Token;
            return result;
        }

        /// <summary>
        /// 写入Cache
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userinfo"></param>
        /// <returns></returns>
        private UserAuthSession SetCache(PassportLoginRequest request, UserInforMations userinfo)
        {
            var currentSession = new UserAuthSession
            {
                Account = userinfo.UserCode,
                Name = userinfo.UserName,
                Token = Guid.NewGuid().ToString().GetHashCode().ToString("x"),
                AppKey = request.AppKey,
                CreateTime = DateTime.Now,
                IpAddress = _auth.GetIp()
            };
            _cache.Set(currentSession.Token, currentSession, DateTime.Now.AddDays(10));
            return currentSession;
        }
        #endregion

    }
}
